package com.csy.admin.web;


import com.csy.admin.entity.LearningExperience;
import com.csy.admin.service.LearningExperienceService;
import com.csy.admin.util.PageUtils;
import com.csy.admin.util.Result;
import com.csy.common.exception.RRException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  学习经验控制类
 * </p>
 *
 * @author csy
 * @since 2018-09-19
 */
@RestController
@RequestMapping("/learningExperience")
public class LearningExperienceController extends AbstractController{

    @Autowired
    private LearningExperienceService learningExperienceService;

    @RequestMapping(value = "/list")
    public Result list(@RequestParam Map<String,Object> map){
        PageUtils page = learningExperienceService.queryExperienceList(map);
        return Result.ok().put("page",page);
    }

    @RequestMapping(value = "/info/{id}",method = RequestMethod.GET)
    public Result info(@PathVariable("id") Long id){
        LearningExperience experience = learningExperienceService.getById(id);
        return Result.ok().put("dict",experience);
    }
    /**
     * 保存经验
     * @param learningExperience
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result save(@RequestBody LearningExperience learningExperience){
        learningExperience.setCreateTime(new Date());
        learningExperience.setUserId(getUserId());
        learningExperience.setFlagInvalid(0);
        verifyForm(learningExperience);
        learningExperienceService.save(learningExperience);
        return Result.ok();
    }

    /**
     * 修改经验
     * @param learningExperience
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update(@RequestBody LearningExperience learningExperience){
        verifyForm(learningExperience);
        learningExperienceService.updateById(learningExperience);
        return Result.ok();
    }

    /**
     * 验证参数是否正确
     * @param learningExperience
     */
    private void verifyForm(LearningExperience learningExperience){
        if(StringUtils.isBlank(learningExperience.getExperienceTitle())){
            throw new RRException("标题不能为空");
        }

        if(learningExperience.getClassId() == null){
            throw new RRException("分类不能为空");
        }

        if(learningExperience.getTagId() == null){
            throw new RRException("标签不能为空");
        }

        if(learningExperience.getShowType() == null){
            throw new RRException("可见类型不能为空");
        }
    }

    /**
     * 删除经验
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete")
    public Result delete(@RequestBody String[] ids){
        learningExperienceService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }


}

